package com.wondertek.poms.core.service.impl;

import cn.hutool.core.util.StrUtil;
import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.utils.CopyUtils;
import com.wondertek.poms.core.service.IPcProductPermissionService;
import com.wondertek.poms.dao.po.PcProductPermission;
import com.wondertek.poms.dao.repo.IPcProductPermissionDao;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * <p><b>PcProductPermissionServiceImpl Description:</b> 产品权限表service层实现 </p>
 * @author 窦再兴
 * <p><b>DATE</b> 2019-08-12 11:20:53</p>
 */
@Service
@Scope("prototype")
public class PcProductPermissionServiceImpl extends ServiceImpl<PcProductPermission, Long> implements IPcProductPermissionService {
	@PersistenceContext
    public EntityManager entityManager;

	@Autowired
	IPcProductPermissionDao iPcProductPermissionDao;

	private String sql = "select fs_prd_id from pc_product_permission WHERE prd_level = ";

	@Override
	@Transactional
	public PcProductPermission deleteLogic(Long id) {

		PcProductPermission cp = jpaRepository.getOne(id);
		PcProductPermission.putTimeAndUser(cp);
		cp.setDeleted(Constants.DELETE_1);
		jpaRepository.save(cp);
		return cp;
	}

	@Override
	@Transactional
	public PcProductPermission merge(PcProductPermission model) {
		PcProductPermission.putTimeAndUser(model);
		PcProductPermission dbo = jpaRepository.getOne(model.getId());
		CopyUtils.copyProperties(model, dbo);
		return jpaRepository.save(dbo);
	}

	@Override
	public String getFirstProductInfoPackageIds(String userId, String groupIds) {
		String condition =getSqlCondition(userId, groupIds);
		//查询一级产品时，prd_level = 1
		return getResultIdString(sql+"1 "+condition);
	}
	@Override
	public String getProductInfoPackageIds (String userId, String groupIds){
		String condition =getSqlCondition(userId, groupIds);
		//查询二级产品时，prd_level = 2
		return getResultIdString(sql+"2 "+condition);
	}

	@Override
	public String getPrdInfoIds (String userId, String groupIds){
		String condition =getSqlCondition(userId, groupIds);
		//查询商品包时，prd_level = 3
		return getResultIdString(sql+"3 "+condition);
	}

	//sql查询，获取结果id列表,并组装成String
	private String getResultIdString(String sql){
		Query query = entityManager.createNativeQuery(sql);
		StringBuffer idString =  new StringBuffer();
		List<Object> resultList = query.getResultList();
		if (resultList == null || resultList.size() == 0) {
			return null;
		}
		for (Object o : resultList) {
			idString.append(o.toString()+",");
		}
		int length = idString.toString().length();
		return  idString.toString().substring(0,length-1);
	}

	//根据userId和groupIds，获取查询条件condition
	private String getSqlCondition(String userId, String groupIds){
		StringBuffer condition = new StringBuffer();
		if (StrUtil.isNotBlank(userId) && StrUtil.isBlank(groupIds)) {
			condition.append(" and user_type = 1 and ugid = ").append(userId);
		}
		if (StrUtil.isNotBlank(userId) && StrUtil.isNotBlank(groupIds)) {
			condition.append(" and ((user_type = 1 and ugid = ").append(userId + ") ");
			condition.append(" or (user_type = 2 and ugid in (").append(groupIds + "))) ");
		}
		condition.append(" and deleted = 0 ");
		return  condition.toString();
	}



	@Override
	public Page<PcProductPermission> findAll(PcProductPermission entity, int page, int rows, String sord, String sidx) {
		Pageable pageable = getPageable(page - 1, rows, sidx, sord);
        CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
        CriteriaQuery<PcProductPermission> criteriaQuery= criteriaBuilder.createQuery(PcProductPermission.class);
        Root<PcProductPermission> root= criteriaQuery.from(PcProductPermission.class);
		criteriaQuery.distinct(true).multiselect(root.get("ugid"),root.get("ugname"),root.get("userType"));
        List<Predicate> list=new ArrayList<>();
        if(null!=entity.getUgid()){
            list.add(criteriaBuilder.equal(root.get("ugid").as(Long.class),entity.getUgid()));
        }
        if(StringUtils.isNotBlank(entity.getUgname())){
            list.add(criteriaBuilder.like(root.get("ugname").as(String.class),"%"+entity.getUgname()+"%"));
        }
		list.add(criteriaBuilder.equal(root.get("deleted"),0));
        criteriaQuery.where(criteriaBuilder.and(list.toArray(new Predicate[list.size()])));
		List<PcProductPermission>  counts=entityManager.createQuery(criteriaQuery).getResultList();
        TypedQuery<PcProductPermission>  createQuery=entityManager.createQuery(criteriaQuery);
		createQuery.setFirstResult((page-1)*rows);
		createQuery.setMaxResults(rows);
		 return  new PageImpl<>(createQuery.getResultList(),pageable,counts.size());
	}


}